<?php

namespace App\Service\Workflow;

use App\Enums\Workflow\WorkflowEnum;
use App\Enums\Workflow\WorkflowV2Enum;
use App\Library\FeiShu\SendFs;
use App\Library\Rms\RmsUserApi;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\Common\OpenShopOrderManagerModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopAddressModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\Workflow\WorkflowOrderLogModel;
use App\Models\Workflow\WorkflowOrderModel;
use App\Models\Workflow\WorkflowOrderNodeModel;
use App\Models\Workflow\WorkflowTemplateModel;
use App\Models\Workflow\WorkflowTemplateNodeModel;
use App\Models\Workflow\WorkflowV2OrderLogModel;
use App\Models\Workflow\WorkflowV2OrderModel;
use App\Models\Workflow\WorkflowV2OrderNodeHandlerModel;
use App\Models\Workflow\WorkflowV2OrderNodeModel;
use App\Models\Workflow\WorkflowV2TemplateModel;
use App\Models\Workflow\WorkflowV2TemplateNodeModel;
use App\Models\WorkOrder\WorkflowV2TypeModel;
use App\Service\BaseService;
use App\Service\Cruise\Mission\RenewInputService;
use App\Service\Cruise\Mission\WorkflowV2InputService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\System\SystemNotifyService;
use App\Service\Workflow\Type\RenewTypeService;
use App\Support\CustomForm\AttributeSupport;
use App\Service\WorkOrder\WorkOrderBaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Kuafu\GeneralFs\BuildFs;
use Ritaswc\LarkCardMessageBuilder\CardMessageBuilder;
use Ritaswc\LarkCardMessageBuilder\Element\Hr;
use Ritaswc\LarkCardMessageBuilder\Tag;

class WorkflowV2OrderService extends BaseService
{
    private WorkflowV2OrderModel      $workflowV2OrderModel;
    private ?OpenShopMainProcessModel $openShopMainProcessModel;
    private int $userId;

    public function __construct(int $id = 0, int $userId = 0)
    {
        if ($id) {
            $this->workflowV2OrderModel = WorkflowV2OrderModel::query()->find($id);
        }

        $this->userId = $userId;
    }

    public function getWorkflowV2OrderModel(): WorkflowV2OrderModel
    {
        return $this->workflowV2OrderModel;
    }

    /**
     * 初始化审批流order
     * @param int $workflowType
     * @param int $shopId
     * @param int $relationId
     * @param int $currentUid
     * @param bool $skipFirstCruiseOrder 是否跳过第一个提交表单
     * @return WorkflowOrderModel
     */
    public function init(int $workflowType, int $workflowType2, int $shopId, int $relationId = 0, bool $skipFirstCruiseOrder = false): WorkflowV2OrderModel
    {
        // 校验是否可以发起审批流
//        $this->verifyInit($workflowType, $shopId, $relationId);

        $templateModel = WorkflowV2TemplateModel::query()
                                              ->where('workflowType', $workflowType)
                                              ->when($workflowType2, function ($query) use ($workflowType2) {
                                                  $query->where('workflowType2', $workflowType2);
                                              })
                                              ->where('status', WorkflowTemplateModel::STATUS_ON)
                                              ->orderByDesc('id')
                                              ->first();
        if (!$templateModel) {
            $workflowTypeText = WorkflowV2Enum::WORKFLOW_TYPE_TEXT[$workflowType] ?? '';
            BaseService::throwErr("未找到对应的审批模板:{$workflowTypeText}");
        }

        $this->openShopMainProcessModel = OpenShopMainProcessModel::query()->where('shopId', $shopId)->first();
        if (!$this->openShopMainProcessModel) {
            BaseService::throwErr("shopId:{$shopId}未匹配到开店主单");
        }

        DB::beginTransaction();

        // insert workflow_orders
        $this->workflowV2OrderModel                         = new WorkflowV2OrderModel();
        $this->workflowV2OrderModel->workflowNo             = $this->workflowV2OrderModel->generateWorkflowNo();
        $this->workflowV2OrderModel->name                   = $templateModel->name;
        $this->workflowV2OrderModel->workflowType           = $templateModel->workflowType;
        $this->workflowV2OrderModel->workflowType2          = $templateModel->workflowType2;
        $this->workflowV2OrderModel->status                 = WorkflowOrderModel::STATUS_ING;
        $this->workflowV2OrderModel->shopId                 = $shopId;
        $this->workflowV2OrderModel->relationId             = $relationId;
        $this->workflowV2OrderModel->submitCruiseTemplateId = $templateModel->submitCruiseTemplateId;
        $this->workflowV2OrderModel->currentNodeId          = 0;
        $this->workflowV2OrderModel->save();

        // 因为kfUid insert不进去
        $this->workflowV2OrderModel->createdByUid = $this->userId;
        $this->workflowV2OrderModel->save();

        // insert workflow_order_nodes
        WorkflowV2TemplateNodeModel
            ::query()
            ->where('workflowTemplateId', $templateModel->id)
            ->get()
            ->each(function (WorkflowV2TemplateNodeModel $item, $k) use ($shopId, $skipFirstCruiseOrder) {

                //  初始化自定义表单模板
                $cruiseOrderId = 0;
                if ($item->cruiseTemplateId) {

                    // 跳过初始化第一个提交表单
                    if ($skipFirstCruiseOrder && $k == 0) {
                        return;
                    }

                    $input = (new WorkflowV2InputService(0, $this->userId));
                    $input->initOrderInput($item->cruiseTemplateId);
                    $cruiseOrderId = $input->getCruiseOrderModel()->id;
                }

                // 第一个节点进行中，其余节点待处理
                if ($k == 0) {
                    $status = WorkflowV2OrderNodeModel::STATUS_ING;
                } else {
                    $status = WorkflowV2OrderNodeModel::STATUS_WAIT;
                }

                $orderNode = WorkflowV2OrderNodeModel::query()->create([
                    'workflowOrderId'        => $this->workflowV2OrderModel->id,
                    'workflowTemplateNodeId' => $item->id,
                    'pId'                    => 0,
                    'nextId'                 => 0,
                    'prevId'                 => 0,
                    'name'                   => $item->name,
                    'status'                 => $status,
                    'businessType'           => $item->businessType,
                    'nodeType'               => $item->nodeType,
                    'handlerType'            => $item->handlerType,
                    'cruiseTemplateId'       => $item->cruiseTemplateId,
                    'cruiseOrderId'          => $cruiseOrderId,
                    'condition'              => $item->condition,
                    'createdAt'              => time(),
                    'createdByUid'           => $this->userId,
                    'updatedAt'              => time(),
                    'updatedByUid'           => 0,
                ]);

                if ($k == 0) {

                    // 更新第一个节点
                    $this->workflowV2OrderModel->submitCruiseOrderId = $cruiseOrderId;
                    $this->workflowV2OrderModel->currentNodeId = $orderNode->id;
                    $this->workflowV2OrderModel->save();
                }

                // 计算handlerUids
                $handlerUids = $this->generateHandlerUid($item->handlerType, json_decode($item->handlerUids, true));
                foreach ($handlerUids as $uid) {

                    if ($uid <= 0) {
                        continue;
                    }

                    WorkflowV2OrderNodeHandlerModel::query()->create([
                        'workflowOrderNodeId'    => $orderNode->id,
                        'workflowTemplateNodeId' => $item->id,
                        'handlerType'            => $item->handlerType,
                        'handlerUid'             => $uid,
                    ]);
                }
            });

        // 更新pId/nextId/prevId
        WorkflowV2TemplateNodeModel
            ::query()
            ->where('workflowTemplateId', $templateModel->id)
            ->get()
            ->each(function (WorkflowV2TemplateNodeModel $item, $k) {

                $updateArr = [];

                // 查找对应业务，在order_nodes中的节点id
                $getOrderNodeId = function (string $column) use ($item) {
                    return WorkflowV2OrderNodeModel::query()
                                                 ->where('workflowOrderId', $this->workflowV2OrderModel->id)
                                                 ->where('workflowTemplateNodeId', $item->{$column})
                                                 ->value('id');
                };

                if ($item->pId != 0) {
                    $updateArr['pId'] = $getOrderNodeId('pId');
                }

                if ($item->nextId != 0) {
                    $updateArr['nextId'] = $getOrderNodeId('nextId');
                }

                if ($item->prevId != 0) {
                    $updateArr['prevId'] = $getOrderNodeId('prevId');
                }

                if ($updateArr) {
                    WorkflowV2OrderNodeModel::query()
                                          ->where('workflowOrderId', $this->workflowV2OrderModel->id)
                                          ->where('workflowTemplateNodeId', $item->id)
                                          ->update($updateArr);
                }
            });

        // insert 日志
        $workflowOrderNodeId = $this->workflowV2OrderModel->nodesRel->first()['id']; // 第一个节点id
        (new WorkflowV2OrderLogModel())->add($this->workflowV2OrderModel->id, $workflowOrderNodeId, $this->userId);

        // 同步工单汇总表
        WorkOrderBaseService::syncWorkOrderGather($this->workflowV2OrderModel->workflowNo, $shopId);

        DB::commit();

        return $this->workflowV2OrderModel;
    }

    /**
     * 生成节点处理人
     * @param int $handlerType
     * @param int $handlerUid
     * @return array
     */
    private function generateHandlerUid(int $handlerType, ?array $handlerUids): array
    {
        if ($handlerType == 0) {
            return [];
        }

        // 总部 - 指定用户
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_HEAD) {
            return (array)$handlerUids;
        }

        $mainProcessId = $this->openShopMainProcessModel->id;

        // 督导
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_SUPERVISE) {
            $type = OpenShopOrderManagerModel::MANAGER_TYPE_5;
            return [(int)OpenShopOrderManagerModel::getManagerUid($mainProcessId, $type)];
        }

        // 省总
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_PROVINCE) {
            $addressModel = OpenShopAddressModel::getData($this->openShopMainProcessModel->orderNo);
            if (!$addressModel) {
                BaseService::throwErr("{$this->openShopMainProcessModel->orderNo}未找到地址信息");
            }

            return [(int)OrganizationManageService::getProvinceInfoByProvinceCode($addressModel->provinceCode)['operationUid'] ?? 0];
        }

        // 加盟商本人
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_MERCHANT) {
            return [(int)optional($this->openShopMainProcessModel->signOrderRel)->merchantUserId];
        }

        // 门店店长
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_SHOP_MANAGER) {
            return []; // TODO 后面实时查询rms
        }

        // 提交人
        if ($handlerType == WorkflowV2Enum::HANDLER_TYPE_SUBMITTER) {
            return [$this->userId];
        }

        return [];
    }

    /**
     * 获取当前进行中节点信息
     */
    public function getCurrentNode(): ?WorkflowV2OrderNodeModel
    {
        return WorkflowV2OrderNodeModel::query()
                                       ->where('workflowOrderId', $this->workflowV2OrderModel->id)
                                       ->where('status',  WorkflowEnum::NODE_STATUS_ING)
                                       ->first();
    }
//
//    /**
//     * 确认处理人
//     * @return $this
//     */
//    public function checkHandlerUid(int $uid): self
//    {
//        $ingNodes = $this->getCurrentNodes();
//
//        $flag = false;
//        foreach ($ingNodes as $node) {
//
//            if ($node->handlerUid == $uid) {
//                $flag = true;
//                break;
//            }
//        }
//
//        if (!$flag) {
//            BaseService::throwErr('不是该节点的处理人:'. $node->handlerUid);
//        }
//
//        return $this;
//    }
//
    /**
     * 完成当前节点，并切换到下个节点
     * @param int $nodeId
     * @return WorkflowOrderNodeModel|null
     */
    public function finishNodeEnterNext(
        int $nodeId,
        int $audit = 0,
        string $content = '',
        int $rejectNodeId = 0
    ): ?WorkflowV2OrderNodeModel {
        $currentNode = $this->getCurrentNode();
        if (!$currentNode) {
            BaseService::throwErr('当前节点不在进行中');
        }

        // 用户完成
        WorkflowV2OrderNodeHandlerModel::finish($currentNode->id, $this->userId);

        // TODO 驳回操作 - 把当前->驳回指定节点中的节点，全部置为待处理状态
        if ($audit == WorkflowV2OrderLogModel::AUDIT_NO) {

            $this->rejectNode();

            return null;
        }

        if ($audit == WorkflowV2OrderLogModel::AUDIT_NO && $rejectNodeId) {
            $nextNodeId = $rejectNodeId;
        } else {

            // 获取下个节点
            $nextNodeId = $this->calcNextMainNodeId($currentNode);
        }

        if ($nextNodeId != -1) {

            // 此节点 - 更新为完成状态
            $currentNode->status = WorkflowV2OrderNodeModel::STATUS_FINISH;
            $currentNode->save();

            $this->finishApprovalFs(true);
        }

        // 此节点 - 日志更新为完成状态
        // TODO 下个节点 - 日志待处理状态
//        (new WorkflowV2OrderLogModel())->finish($this->workflowV2OrderModel->id, $nodeId, $this->userId, $nextNodeId, $audit, $content, $rejectNodeId);

        // 没有下个节点 - 审批流结束
        if ($nextNodeId == 0) {
            $this->workflowV2OrderModel->status        = WorkflowV2OrderModel::STATUS_FINISH;
            $this->workflowV2OrderModel->currentNodeId = 0;
            $this->workflowV2OrderModel->save();
            return null;
        }

        // 会签 - 还有流程没走完
        if ($nextNodeId == -1) {
            return $currentNode;
        }

        // 更新当前节点id
        $this->workflowV2OrderModel->currentNodeId = $nextNodeId;
        $this->workflowV2OrderModel->save();

        // 当前节点是抄送 - 处理抄送逻辑
        if ($currentNode->nodeType == WorkflowV2Enum::NODE_TYPE_CC) {

            // 审批日志完成
            $log = (new WorkflowV2OrderLogModel());
            $log->add($this->workflowV2OrderModel->id, $currentNode->id, 0, WorkflowV2OrderLogModel::AUDIT_YES);
            $log->add($this->workflowV2OrderModel->id, $nextNodeId, 0);

            // 抄送
            $ccConfig = (array)json_decode($currentNode->ccInfo, true);
            $orderModel = $this->workflowV2OrderModel;

            dispatch(function () use ($orderModel, $ccConfig) {
                (new WorkflowV2OrderCCService($orderModel, $ccConfig))->handle();
            });
        }

        // 下个节点进入进行中
        $nextNode = WorkflowV2OrderNodeModel::query()->where('id', $nextNodeId)->first();
        if (!$nextNode) {
            BaseService::throwErr("未找到下个节点{$nextNodeId}");
        }

        // 下个节点开启
        $nextNode->status = WorkflowV2OrderNodeModel::STATUS_ING;
        $nextNode->save();

        // 递归处理抄送&分支节点
        if ($audit == WorkflowV2OrderLogModel::AUDIT_YES) {

            // 当前节点完成 - 推送下个节点的待审批状态
            $this->waitApprovalFs($nextNode);

            if (in_array($nextNode->nodeType, [
                WorkflowV2Enum::NODE_TYPE_IF_BRANCH,
                WorkflowV2Enum::NODE_TYPE_IF_MAIN,
                WorkflowV2Enum::NODE_TYPE_CC
            ])) {
                return $this->finishNodeEnterNext($nextNodeId, $audit, '', 0);
            }
        }

        // 节点完成后的操作
//        dispatch(function () use ($nextNode, $audit) {
//            RenewTypeService::getIns($this->workflowV2OrderModel->workflowType, $this, $nextNode)
//                            ->finishNode($audit);
//        });

        return $nextNode;
    }

    // 获取下个节点
    private function calcNextMainNodeId(WorkflowV2OrderNodeModel $currentNode)
    {
        // 顺序、或签 -> 进入下一步
        if (in_array($currentNode->nodeType, [WorkflowV2Enum::NODE_TYPE_OR, WorkflowV2Enum::NODE_TYPE_SEQUENCE])) {
            return $currentNode->nextId;
        }


        // 会签
        if ($currentNode->nodeType == WorkflowV2Enum::NODE_TYPE_AND) {

            // 查询处理人
            $handlerCount = WorkflowV2OrderNodeHandlerModel::query()
                                                           ->where('workflowOrderNodeId', $currentNode->id)
                                                           ->where('handlerStatus', WorkflowV2OrderNodeHandlerModel::HANDLER_STATUS_WAIT)
                                                           ->count();
            if ($handlerCount == 0) {

                // 会签完成
                return $currentNode->nextId;
            } else {

                // 会签还有节点未结束
                return -1;
            }
        }

        // 抄送
        if ($currentNode->nodeType == WorkflowV2Enum::NODE_TYPE_CC) {
            return $currentNode->nextId;
        }

        // 条件父节点
        if ($currentNode->nodeType == WorkflowV2Enum::NODE_TYPE_IF_MAIN) {

            $nextId = $this->matchIfConditionGetNextId($currentNode);

            if ($nextId === null) {
                $workflowTemplateId = (int)WorkflowTemplateNodeModel::query()
                                                                    ->where('id', $currentNode->workflowTemplateNodeId)
                                                                    ->value('workflowTemplateId');

                // 没匹配到规则，报警
                BuildFs::newRobot(SendFs::ROBOT_WARNING)
                       ->setTitleContent("审批流v 分支条件没匹配到规则", "当前节点id:{$currentNode->id} 审批流模板id:{$workflowTemplateId}")
                       ->setAtUid('9efgbcdb', '2c54915f')
                       ->send();

                BaseService::throwErr('未命中条件节点规则，请联系管理员');
            }

            return $nextId;
        }

        // 条件子节点
        if ($currentNode->nodeType == WorkflowV2Enum::NODE_TYPE_IF_BRANCH) {
            return $currentNode->nextId;
        }

        BaseService::throwErr('未知节点类型');
    }

    /**
     * 匹配分支节点的条件，并返回下个节点id
     * @param WorkflowV2OrderNodeModel $currentNode
     * @return int|null
     */
    private function matchIfConditionGetNextId(WorkflowV2OrderNodeModel $parentIfNode): ?int
    {
        // 主表单信息
        $inputs = (new WorkflowV2InputService($this->workflowV2OrderModel->submitCruiseOrderId, $this->userId))
            ->getInputObjectFill()['lists'] ?? [];

        // 找到所有pid = 当前节点id的节点
        $nextId = null;
        WorkflowV2OrderNodeModel::query()
                                ->where('pId', $parentIfNode->id)
                                ->get()
                                ->each(function ($item) use ($inputs, &$nextId) {

                                    // condition
                                    $conditions = json_decode($item->condition, true);
                                    if (!$conditions) {
                                        return;
                                    }

                                    foreach ($conditions as $condition) {

                                        foreach ($inputs as $positions) {
                                            foreach ($positions['projects'] as $project) {

                                                if ($project['projectId'] == $condition['projectId']) {

                                                    $result = false;

                                                    switch ($condition['formula']) {
                                                        case WorkflowV2Enum::FORMULA_EQUALS:
                                                            $result = $project['value'] == $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_GT:
                                                            $result = $project['value'] > $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_GT_EQ:
                                                            $result = $project['value'] >= $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_LT:
                                                            $result = $project['value'] < $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_LT_EQ:
                                                            $result = $project['value'] <= $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_UNEQUALS:
                                                            $result = $project['value'] != $condition['optionsValue'];
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_IN:
                                                            $result = in_array($project['value'], (array)$condition['optionsValue']);
                                                            break;
                                                        case WorkflowV2Enum::FORMULA_NOT_IN:
                                                            $result = !in_array($project['value'], (array)$condition['optionsValue']);
                                                            break;
                                                    }

                                                    if ($result) {
                                                        $nextId = $item->id;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                });

        return $nextId;
    }
//
//    /**
//     * 可驳回的节点ids
//     * @return array
//     */
//    public function rejectNodeLists(): array
//    {
//        $currentNode = $this->getCurrentMainNode();
//        if (!$currentNode) {
//            return [];
//        }
//
//        $currentNodeId = $currentNode->id;
//
//        $rejectNodeLists = [];
//
//        // 从后往前遍历
//        WorkflowOrderNodeModel::query()
//                              ->where('workflowOrderId', $this->workflowV2OrderModel->id)
//                              ->orderByDesc('id')
//                              ->get()
//                              ->each(function (WorkflowOrderNodeModel $workflowOrderNodeModel) use (
//                                  &$currentNodeId,
//                                  &$rejectNodeLists
//                              ) {
//                                  if ($workflowOrderNodeModel->nextId == $currentNodeId && $workflowOrderNodeModel->pId == 0) {
//                                      $rejectNodeLists[] = [
//                                          'id' => $workflowOrderNodeModel->id,
//                                          'name' => $workflowOrderNodeModel->name,
//                                      ];
//
//                                      $currentNodeId = $workflowOrderNodeModel->id;
//                                  }
//
//                              });
//
//
//        return array_reverse($rejectNodeLists);
//    }
//

    /**
     * 驳回
     * @return void
     */
    private function rejectNode(): void
    {
        // 工单类型 - 直接创建一个新的审批，并且把初始表单cruiseOrder同步过去
        if ($this->workflowV2OrderModel->workflowType == WorkflowV2Enum::WORKFLOW_TYPE_WORK_ORDER) {

            // 当前审批流关闭
            $this->workflowV2OrderModel->status = WorkflowV2OrderModel::STATUS_CLOSE;
            $this->workflowV2OrderModel->save();

            // 创建新的审批
            $newOrder = (new WorkflowV2OrderService(0, $this->userId))->init(
                $this->workflowV2OrderModel->workflowType,
                $this->workflowV2OrderModel->workflowType2,
                $this->workflowV2OrderModel->shopId,
                $this->workflowV2OrderModel->relationId,
                true
            );

            // 同步表单
            $newOrder->submitCruiseOrderId = $this->workflowV2OrderModel->submitCruiseOrderId;
            $newOrder->save();

            // 同步第一个节点的表单
            $firstNode = $newOrder->nodesRel->first();
            $firstNode->cruiseOrderId = $this->workflowV2OrderModel->submitCruiseOrderId;
            $firstNode->save();
        }

        // 驳回 - 推送给提交人
        $this->finishApprovalFs(false);
    }


    /**
     * 下个节点 - 待审批的飞书推送
     * @return void
     */
    public function waitApprovalFs(WorkflowV2OrderNodeModel $workflowV2OrderNodeModel)
    {
        $workflowV2OrderModel = $this->workflowV2OrderModel;

        dispatch(function () use ($workflowV2OrderNodeModel, $workflowV2OrderModel) {

            // 节点的处理人
            // TODO 要考虑实时性吗？
            $waitHandlerUids = $workflowV2OrderNodeModel->orderNodeHandlersRel->pluck('handlerUid')->unique()->values()->toArray();
            if (!$waitHandlerUids) {
                return;
            }

            Log::info("v2WaitApprovalFs", ['waitHandlerUids' => $waitHandlerUids, 'workflowV2OrderNodeId' => $workflowV2OrderNodeModel->id]);

            $cardMessageBuilder = self::getWebFsCardArr($this->workflowV2OrderModel);

            BuildFs::newRobot('center', BuildFs::MSG_TYPE_CARD, BuildFs::MODULE_TYPE_APP)
                   ->setCardContent($cardMessageBuilder)
                   ->setUserIds($waitHandlerUids)
                   ->send();
        });
    }

    /**
     * 获取web飞书卡片内容
     * @param WorkflowV2OrderModel $workflowV2OrderModel
     * @return array
     */
    public static function getWebFsCardArr(WorkflowV2OrderModel $workflowV2OrderModel): array
    {
        $url = \App\Service\OpenShop\Feishu\BaseService::commonWebUrl("/work-flow/order/detail?id={$workflowV2OrderModel->id}");

        // 基础信息
        $shopInfo = vsprintf("%s%s", [
            (string)optional($workflowV2OrderModel->shopRel)->shopCode,
            (string)optional($workflowV2OrderModel->shopRel)->name
        ]);
        $problemTypeName = (string)WorkflowV2TypeModel::query()->where('id', $workflowV2OrderModel->workflowType2)->value('name');
        $createdUserName = (new RmsUserApi())->getUserInfoByIds([$workflowV2OrderModel->createdByUid])['data'][0]['username'] ?? '-';

        // 表单内容
        $inputContents = [];
        $inputs = (new WorkflowV2InputService($workflowV2OrderModel->submitCruiseOrderId, 0))->inputArray();
        foreach ($inputs as $input) {

            if ($input['value'] === null || $input['value'] === '') {
                continue;
            }

            switch ($input['inputType']) {
                case AttributeSupport::INPUT_TYPE_RADIO:
                case AttributeSupport::INPUT_TYPE_SELECT:

                    $value = collect($input['customAttributes']['options'])->where('value', $input['value'])->pluck('text')->first();

                    $inputContents[] = ['name' => $input['text'], 'value' => $value];

                    break;
                case AttributeSupport::INPUT_TYPE_SELECT_MULTIPLE:

                    $value = collect($input['customAttributes']['options'])->whereIn('value', $input['value'])->pluck('text')->implode(',');

                    $inputContents[] = ['name' => $input['text'], 'value' => $value];

                    break;

            }

            if (is_scalar($input['value'])) {
                $inputContents[] = ['name' => $input['text'], 'value' => $input['value']];
            }

            if (count($inputContents) >=3 ) {
                break;
            }
        }

        $cardMessageBuilder = (new CardMessageBuilder(sprintf('%s"%s"工单需处理', $shopInfo, $problemTypeName)))
            ->template('blue')
            ->addElement(Tag::divMarkdown("**申请人**"))
            ->addElement(Tag::divMarkdown($createdUserName))
            ->addElement(Tag::divMarkdown("**提交内容**"));

        foreach ($inputContents as $content) {
            $cardMessageBuilder = $cardMessageBuilder->addElement(Tag::divMarkdown($content['name'] . "：" . $content['value']));
        }

        return $cardMessageBuilder
            ->addElement(Tag::divMarkdown("**提交时间**"))
            ->addElement(Tag::divMarkdown(date('Y-m-d H:i:s')))
            ->addElement(Tag::hr())
            ->addElement(Tag::actions()->addAction(Tag::button()->url($url)->text('立即处理')))
            ->build();
    }

    /**
     * 已完成的商家推送
     * @param int $userId
     * @param bool $finish false结束/驳回 true完成
     * @return void
     */
    public function finishApprovalFs(bool $finish): void
    {
        $url = config('webUrl.notify_web_cdn_url') . "#/pages/work-order/work-flow/progress-detail?workOrderNo={$this->workflowV2OrderModel->workflowNo}";

        // 基础信息
        $shopInfo = vsprintf("%s%s", [
            (string)optional($this->workflowV2OrderModel->shopRel)->shopCode,
            (string)optional($this->workflowV2OrderModel->shopRel)->name
        ]);

        if ($finish) {
            $title = "“{$this->workflowV2OrderModel->name}”工单已处理完成通知";
            $content = "尊敬的夸父伙伴您好，您于 {$this->workflowV2OrderModel->createdAt->toDateTimeString()} 提交的“{$this->workflowV2OrderModel->name}”工单（ID：{$this->workflowV2OrderModel->workflowNo}），已处理完成，请点击查看详情。【{$shopInfo}】";
        } else {
            $title = "“{$this->workflowV2OrderModel->name}”工单已关闭通知";
            $content = "尊敬的夸父伙伴您好，您于 {$this->workflowV2OrderModel->createdAt->toDateTimeString()} 提交的“{$this->workflowV2OrderModel->name}”工单（ID：{$this->workflowV2OrderModel->workflowNo}），客服已处理回复相关信息，请点击查看详情。【{$shopInfo}】";
        }

        $shopInfo = $this->workflowV2OrderModel->shopRel;
        $shopName = $shopInfo->shopCode . $shopInfo->name;

        // 向商家发送报名消息
        $notify = SystemNotifyService::save(
            false,
            $title,
            SystemNotifyCenterModel::NOTIFY_TYPE_2,
            $this->workflowV2OrderModel->createdByUid ? SystemNotifyCenterModel::NOTIFY_TARGET_3 : SystemNotifyCenterModel::NOTIFY_TARGET_1,
            '',
            $title,
            $url,
            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
            $content,
            $content,
            SystemNotifyCenterModel::IS_POPUP_ON,
            1,
            $this->workflowV2OrderModel->shopId,
        );
        SystemNotifyService::recordLog($notify, '创建消息');

        SystemNotifyService::preSend($notify->id, [$this->workflowV2OrderModel->createdByUid]);
    }

}
